import { getUserTempId } from '@/utils/userAbout'
import { reqGetCode, reqUserRegister, reqUserLogin, reqGetUserInfo ,reqUserLogout} from '@/api'
const state = {
    //用户临时标识
    userTempId: getUserTempId(),
    //验证码
    code: '',
    //token
    token: localStorage.getItem('TOKEN_KEY'),
    //用户信息
    userInfo: {}
}
const mutations = {
    //验证码
    RECEIVE_CODE(state, code) {
        state.code = code
    },

    //token
    RECEIVE_TOKEN(state, token) {
        state.token = token
    },

    //用户信息
    RECEIVE_USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },

    //清空token
    RESET_TOKEN(state) {
        state.token = '',
        state.userInfo={}
    }
}
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        const result = await reqGetCode(phone)
        if (result.code === 200) {
            commit('RECEIVE_CODE', result.data)
            return result.data
        } else {
            return Promise.reject(new Error('failed'))
        }
    },

    //用户注册
    async userRegister({ commit }, userInfo) {
        const result = await reqUserRegister(userInfo)
        if (result.code === 200) return 'succeed'
        else return Promise.reject(new Error('failed'))
    },

    //用户登录
    async userLogin({ commit }, userInfo) {
        const result = await reqUserLogin(userInfo)
        if (result.code === 200) {
            //将token存储到state中
            commit('RECEIVE_TOKEN', result.data.token)

            //将token存储到localStorage中
            localStorage.setItem('TOKEN_KEY', result.data.token)

            return 'succeed'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },

    //获取用户信息
    async getUserInfo({ commit }) {
        const result = await reqGetUserInfo()
        if (result.code === 200) {
            commit('RECEIVE_USERINFO', result.data)
            return 'succeed'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },

    //清空token
    removeToken({ commit }) {
        commit('RESET_TOKEN')
        localStorage.removeItem('TOKEN_KEY')
    },

    //退出登录
    async userLogout({commit,dispatch}) {
        const result = await reqUserLogout()
        if (result.code === 200) { 
            //清空token
            dispatch('removeToken')
            return 'susseed'
         }
        else return Promise.reject(new Error('failed'))
    }

}
const getters = {

}

export default {
    state,
    mutations,
    actions,
    getters,
}